import random

from src.common.core import TypeCast
from src.common.utils.serial.SerialUtil import SerialUtil
from protocol.SerialProtocol import SerialProtocol
sp = SerialProtocol()
dic = {'ctrl': 1, 'light_swich1': random.randint(0, 1), 'light_power1': random.randint(0, 3), 'light_swich2': random.randint(0, 1), 'light_power2': random.randint(0, 3),
       'light_swich3': random.randint(0, 1), 'light_power3': random.randint(0, 3), 'light_swich4': random.randint(0, 1), 'light_power4': random.randint(0, 3),
       'motorState': random.randint(0, 3), 'temp1': random.randint(0, 65535), 'temp2': random.randint(0, 65535),
       'temp3': random.randint(0, 65535), 'pressure': random.randint(0, 65535), 'meters': random.randint(0, 99999),
       'gasPump': [1, 2, 5, 7][random.randint(0, 3)], 'gasPumpSpeed': random.randint(0, 100),
       'motor': [1, 2, 5, 7][random.randint(0, 3)], 'motorSpeed': random.randint(0, 10000)}
sp.useProtocolDict(dic)

def onMessage(data):
    if (data == b"\x5a\x81\x00\x31\x83"):
        data = sp.makeProtoData()
        data = TypeCast.instance.hexByteStrToHexStrOnlyValue(data)
        str = ""
        for item in data:
            str += item

        su.pub(str.encode())
        print(sp.toDict())
    else:
        data = TypeCast.instance.hexByteStrToHexStrOnlyValue(data)
        str = ""
        for item in data:
            str += item
        sp.parseProtoData(str.encode())
        print("\n当前状态："+sp.toString()+"\n")

su = SerialUtil()
su.onMessage = onMessage
su.timeout = 0.1
su.readLen = 0

if __name__ == '__main__':
    su.open("COM1")
    su.subByThreadStart()
    while True:
        sp.meters = int(input("please set meters:"))





